package yuudachi.dogpoop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class DogPoopActivity extends ListActivity {
	
	List<String> households = new ArrayList();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
		URLConnection conn = null;
		try {
			// Construct data
			String data = URLEncoder.encode("query", "UTF-8") + "="
					+ URLEncoder.encode("select * from household");
			URL url = new URL("http://138.23.220.114:8081/dogpoop/");
			conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(
					conn.getOutputStream());
			wr.write(data);
			wr.flush();

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				//android.util.Log.d("test", line.toString());
				households.add(line);
			}
			android.util.Log.d("test", ((Integer)households.size()).toString());
			wr.close();
			rd.close();
		}
		catch(Exception e){
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			try {
				Integer statusCode = httpConn.getResponseCode();
				InputStream is = httpConn.getErrorStream();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				android.util.Log.d("error", statusCode.toString());		
				String line;
				while ((line = br.readLine()) != null) {
					android.util.Log.d("error", line);	
				}
			} catch (IOException e1) {
				android.util.Log.d("error", "Could not retrieve error");	
			}
		}
		
		
        
        setListAdapter(new ArrayAdapter<String>(this,R.layout.main,households));
    }
}